from SimPy.Simulation import *
from SimPy.SimPlot import *
from random import Random, expovariate, uniform

gen = Random(1337)
avgReturn = []
avgLength = []
nsim = 50000
nstep = 20
for step in range(1,1+nstep):
	pout = 1.0 / float(nstep) * step 
	returns = 0
	length = 0
	for i in range(0, nsim):
		node = 0
		while 1:
			rnd = gen.random()
			if rnd < pout:
				break
			elif rnd < 0.5 * pout + 0.5:
				node = (node + 1) % 3
			else:
				node = (node + 2) % 3
			length += 1
		if node == 0:
			returns += 1
	avgReturn.append([pout, float(returns)/float(nsim)])
	avgLength.append([pout, float(length)/float(nsim)])

for i in range(nstep):
	print "%.2f\tavglength %.4f\tavgreturn %.4f"%(avgLength[i][0],avgLength[i][1],avgReturn[i][1])

plt=SimPlot()
plt.plotLine(avgReturn,title="Fraction exiting from starting point",color="blue",width=2,smooth=True)
plt.plotLine(avgLength,title="Average number of roads taken",color="blue",width=2,smooth=True)
plt.mainloop()
